package com.yupi.yuoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.dto.learninghistory.LearningHistoryQueryRequest;
import com.yupi.yuoj.model.entity.Content;
import com.yupi.yuoj.model.entity.LearningHistory;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.model.vo.ContentVO;
import com.yupi.yuoj.model.vo.LearningHistoryVO;
import com.yupi.yuoj.model.vo.UserVO;
import com.yupi.yuoj.service.ContentService;
import com.yupi.yuoj.service.LearningHistoryService;
import com.yupi.yuoj.mapper.LearningHistoryMapper;
import com.yupi.yuoj.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author admin
* @description 针对表【learning_history(学习历史表)】的数据库操作Service实现
* @createDate 2025-11-01 21:28:44
*/
@Service
public class LearningHistoryServiceImpl extends ServiceImpl<LearningHistoryMapper, LearningHistory>
    implements LearningHistoryService{

    @Resource
    private UserService userService;

    @Resource
    private ContentService contentService;

    @Override
    public void validLearningHistory(LearningHistory learningHistory, boolean add) {
        if (learningHistory == null) {
            throw new RuntimeException(ErrorCode.PARAMS_ERROR.getMessage());
        }
        Long contentId = learningHistory.getContent_id();
        Integer progress = learningHistory.getProgress();
        Integer studyDuration = learningHistory.getStudy_duration();

        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(ObjectUtils.anyNull(contentId, progress, studyDuration), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (contentId != null && contentId <= 0) {
            throw new RuntimeException(ErrorCode.PARAMS_ERROR.getMessage());
        }
        if (progress != null && (progress < 0 || progress > 100)) {
            throw new RuntimeException(ErrorCode.PARAMS_ERROR.getMessage());
        }
        if (studyDuration != null && studyDuration < 0) {
            throw new RuntimeException(ErrorCode.PARAMS_ERROR.getMessage());
        }
    }

    @Override
    public QueryWrapper<LearningHistory> getQueryWrapper(LearningHistoryQueryRequest learningHistoryQueryRequest) {
        QueryWrapper<LearningHistory> queryWrapper = new QueryWrapper<>();
        if (learningHistoryQueryRequest == null) {
            return queryWrapper;
        }
        Long id = learningHistoryQueryRequest.getId();
        Long contentId = learningHistoryQueryRequest.getContentId();
        Long userId = learningHistoryQueryRequest.getUserId();
        String contentType = learningHistoryQueryRequest.getContentType();
        String contentCategory = learningHistoryQueryRequest.getContentCategory();
        Integer minProgress = learningHistoryQueryRequest.getMinProgress();
        Integer maxProgress = learningHistoryQueryRequest.getMaxProgress();
        String sortField = learningHistoryQueryRequest.getSortField();
        String sortOrder = learningHistoryQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(contentId), "content_id", contentId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "user_id", userId);
        queryWrapper.ge(ObjectUtils.isNotEmpty(minProgress), "progress", minProgress);
        queryWrapper.le(ObjectUtils.isNotEmpty(maxProgress), "progress", maxProgress);
        queryWrapper.eq("is_delete", false);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public LearningHistoryVO getLearningHistoryVO(LearningHistory learningHistory, HttpServletRequest request) {
        LearningHistoryVO learningHistoryVO = LearningHistoryVO.objToVo(learningHistory);
        long learningHistoryId = learningHistory.getId();
        // 1. 关联查询用户信息
        Long userId = learningHistory.getUser_id();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        learningHistoryVO.setUser(userVO);
        // 2. 关联查询内容信息
        Long contentId = learningHistory.getContent_id();
        Content content = null;
        if (contentId != null && contentId > 0) {
            content = contentService.getById(contentId);
        }
        ContentVO contentVO = contentService.getContentVO(content, request);
        learningHistoryVO.setContent(contentVO);
        return learningHistoryVO;
    }

    @Override
    public Page<LearningHistoryVO> getLearningHistoryVOPage(Page<LearningHistory> learningHistoryPage, HttpServletRequest request) {
        List<LearningHistory> learningHistoryList = learningHistoryPage.getRecords();
        Page<LearningHistoryVO> learningHistoryVOPage = new Page<>(learningHistoryPage.getCurrent(), learningHistoryPage.getSize(), learningHistoryPage.getTotal());
        if (learningHistoryList.isEmpty()) {
            return learningHistoryVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = learningHistoryList.stream()
                .map(LearningHistory::getUser_id)
                .collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 关联查询内容信息
        Set<Long> contentIdSet = learningHistoryList.stream()
                .map(LearningHistory::getContent_id)
                .collect(Collectors.toSet());
        Map<Long, List<Content>> contentIdContentListMap = contentService.listByIds(contentIdSet).stream()
                .collect(Collectors.groupingBy(Content::getId));
        // 填充信息
        List<LearningHistoryVO> learningHistoryVOList = learningHistoryList.stream()
                .map(learningHistory -> {
                    LearningHistoryVO learningHistoryVO = LearningHistoryVO.objToVo(learningHistory);
                    Long userId = learningHistory.getUser_id();
                    User user = null;
                    if (userIdUserListMap.containsKey(userId)) {
                        user = userIdUserListMap.get(userId).get(0);
                    }
                    learningHistoryVO.setUser(userService.getUserVO(user));
                    Long contentId = learningHistory.getContent_id();
                    Content content = null;
                    if (contentIdContentListMap.containsKey(contentId)) {
                        content = contentIdContentListMap.get(contentId).get(0);
                    }
                    learningHistoryVO.setContent(contentService.getContentVO(content, request));
                    return learningHistoryVO;
                }).collect(Collectors.toList());
        learningHistoryVOPage.setRecords(learningHistoryVOList);
        return learningHistoryVOPage;
    }
}




